var BusinessOrderForm = function () {
  var NewBusinessOrder = function () {
    var template = /* html */ `
      <div style="padding: 0 10px 5px">
        <div>
          <span>订单编号:</span>
          <el-input v-model="orderNo" size="small" placeholder="请输入新订单编号" style="width:180px"></el-input>
        </div>
        <div style="margin-top:5px;text-align:center">
          <el-button type="primary" size="small" @click="ensure">确定</el-button>
        </div>
      </div>
    `;

    return {
      props: {
        orderForm: {
          type: Object,
          required: true
        }
      },

      data: function () {
        var orderForm = this.orderForm;
        return {
          orderNo: orderForm.orderNo
        };
      },

      methods: {
        ensure: function () {
          var orderNo = this.orderNo;
          if (orderNo.trim() === '') {
            this.$alert('请输入订单编号', '信息');
            return;
          }
          var orderForm = this.orderForm;
          var oldOrderNo = orderForm.getOldData('orderNo');
          if (orderNo === oldOrderNo) {
            this.$alert('输入的订单编号，不能跟之前一样', '信息');
            return;
          }
          this.$emit('new-order', {
            orderNo: orderNo
          });
        }
      },

      template: template
    };
  }();

  var template = /* html */ `
    <div class="business-order-form" v-loading.fullscreen.lock="loading">
      <template v-if="orderForm!==null">
      <div style="margin-bottom:5px" class="order-form-btns">
        <template v-if="type==='approval'">
          <el-button size="medium" type="primary" @click="approvalOrder(1)">审核通过</el-button>
          <el-button size="medium" type="danger" @click="approvalOrder(2)">退回</el-button>
        </template>
        <template v-else-if="type==='applyUpdate'">
          <el-button size="medium" type="primary" @click="ensure()">申请修改</el-button>
        </template>
        <template v-else-if="['add','update'].indexOf(type)!==-1">
          <el-button size="medium" type="primary" @click="ensure()">提交</el-button>
        </template>

        <template v-if="['approval','add'].indexOf(type)===-1">
          <el-button size="medium" type="primary" v-popover:applyPopover>保存为新商务订单</el-button>
          <el-popover ref="applyPopover" v-model="showPopver" placement="bottom" width="270" trigger="click">
            <new-business-order v-if="showPopver" :order-form="orderForm" @new-order="toCreateOrder"></new-business-order>
          </el-popover>
        </template>

        <template v-if="type!=='approval'">
          <el-button size="medium" type="primary" @click="addGlasses">添加老花镜</el-button>
          <el-button size="medium" type="primary" @click="addDeliveryDate">添加交期</el-button>
          <img-button v-model="orderForm.picUrl" size="medium" button-text="设置图片"></img-button>
          <el-button size="medium" type="primary" style="margin-left:10px" @click="settingColConfig">配置列显示</el-button>
        </template>
        <template v-else>
          <img-button readonly v-model="orderForm.picUrl" size="medium" button-text="查看图片"></img-button>
        </template>
      </div>
      <div class="order-form-div">
        <div>
          <el-form inline size="medium" label-width="auto">
            <el-form-item label="订单编号">
              <span v-if="type==='approval'||type==='applyUpdate'">{{orderForm.orderNo}}</span>
              <el-input v-else v-model="orderForm.orderNo" class="form-input"></el-input>
            </el-form-item>
            <el-form-item label="工厂型号">
              <span v-if="type==='approval'||type==='applyUpdate'">{{orderForm.bomOrder.factoryNo}}</span>
              <el-select v-else filterable v-model="orderForm.bomOrder" class="form-input" value-key="factoryNo" @change="bomOrderChange">
                <el-option v-for="order in orderList" :key="order.id" :value="order" :label="order.factoryNo"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="客户">
              <span v-if="type==='approval'" :class="{'has-update':checkUpdate('custmer')}">{{orderForm.custmer}}</span>
              <el-select v-else filterable clearable v-model="orderForm.custmer" class="form-input">
                <el-option v-for="item in custmerList" :key="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="客户型号">
              <span v-if="type==='approval'" :class="{'has-update':checkUpdate('custmerVersionNo')}">{{orderForm.custmerVersionNo}}</span>
              <el-input v-else v-model="orderForm.custmerVersionNo" class="form-input"></el-input>
            </el-form-item>
            <el-form-item label="客户订单号">
              <span v-if="type==='approval'" :class="{'has-update':checkUpdate('custmerOrderNo')}">{{orderForm.custmerOrderNo}}</span>
              <el-input v-else v-model="orderForm.custmerOrderNo" class="form-input"></el-input>
            </el-form-item>
            <el-form-item label="分类">
              <span v-if="type==='approval'" :class="{'has-update':checkUpdate('orderType')}">{{orderForm.orderType}}</span>
              <el-select v-else v-model="orderForm.orderType" class="form-input">
                <el-option v-for="item in orderTypeList" :key="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="交货日期">
              <span v-if="type==='approval'" :class="{'has-update':checkUpdate('deliveryTime')}">{{moment(orderForm.deliveryTime).format('YYYY-MM-DD')}}</span>
              <el-date-picker v-else class="form-input" v-model="orderForm.deliveryTime" type="date" value-format="timestamp" :editable="false"
                :clearable="false">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="总金额">
              <span :class="{'has-update':checkUpdate('orderSumPrice')}">{{totalMomey}}</span>
            </el-form-item>
          </el-form>
        </div>
        <div class="order-form-table">
          <el-table border fit :data="orderForm.orderDataList" style="width: 100%" empty-text="" header-row-class-name="order-form-table-header"
            :cell-class-name="setCellClassName" @row-click="toSelectMaterial">
            <el-table-column label="客户色号" min-width="140px" column-key="customerColor" key="customerColor" header-align="center">
              <template slot-scope="scope">
                <span v-if="type==='approval'">{{scope.row.customerColor}}</span>
                <el-input v-else v-model="scope.row.customerColor" class="table-input" size="mini"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="客户颜色描述" min-width="140px" column-key="customerColorDescription" key="customerColorDescription" header-align="center">
              <template slot-scope="scope">
                <span v-if="type==='approval'">{{scope.row.customerColorDescription}}</span>
                <el-input v-else v-model="scope.row.customerColorDescription" class="table-input" size="mini"></el-input>
              </template>
            </el-table-column>

            <template v-for="(columns,materialType) in tableConfig">
            <el-table-column :resizable="false" :label="materialType" :column-key="'material_'+materialType" :key="'material_'+materialType" align="center">
              <el-table-column v-if="hasField(columns,'materialName')" label="物料名称" min-width="120px" :column-key="'materialName_'+materialType" :key="'materialName_'+materialType" header-align="center">
                <template slot-scope="scope">
                  <span>{{getMaterialInfo(scope.row,materialType,'materialName')}}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="hasField(columns,'materialModel')" label="物料规格" min-width="120px" :column-key="'materialModel_'+materialType" :key="'materialModel_'+materialType" header-align="center">
                <template slot-scope="scope">
                  <span>{{getMaterialInfo(scope.row,materialType,'materialModel')}}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="hasField(columns,'materialProviderName')" label="供应商" min-width="120px" :column-key="'materialProviderName_'+materialType" :key="'materialProviderName_'+materialType" header-align="center">
                <template slot-scope="scope">
                  <span>{{getMaterialInfo(scope.row,materialType,'materialProviderName')}}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="hasField(columns,'materialColor')" label="色号" min-width="120px" :column-key="'materialColor_'+materialType" :key="'materialColor_'+materialType" header-align="center">
                <template slot-scope="scope">
                  <span>{{getMaterialInfo(scope.row,materialType,'materialColor')}}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="hasField(columns,'materialColorDescription')" label="颜色描述" min-width="120px" :column-key="'materialColorDescription_'+materialType" :key="'materialColorDescription_'+materialType" header-align="center">
                <template slot-scope="scope">
                  <span>{{getMaterialInfo(scope.row,materialType,'materialColorDescription')}}</span>
                </template>
              </el-table-column>
            </el-table-column>
            </template>

            <template v-for="glasses in glassesMaterialList">
            <el-table-column min-width="150px" :column-key="'glasses_'+glasses.materialCode" :key="'glasses_'+glasses.materialCode" align="center">
              <div slot="header" class="glasses-material-header">
                <span>{{glasses.materialType}}</span>
                <div class="glasses-material-handle" v-if="type!=='approval'">
                  <span style="color:#ff0000" title="删除" @click="delGlasses(glasses)">
                    <i class="el-icon-close"></i>
                  </span>
                </div>
              </div>
              <template slot-scope="scope">
                <span v-if="type==='approval'">{{scope.row.glassesObj[glasses.materialCode]}}</span>
                <el-input-number v-else v-model="scope.row.glassesObj[glasses.materialCode]" class="table-input" :controls="false" size="mini" :min="1" :precision="0"
                  @change="deliveryCountChange(scope.row)">
                </el-input-number>
              </template>
            </el-table-column>
            </template>

            <el-table-column label="单价" min-width="140px" column-key="unitPrice" key="unitPrice" align="center">
              <template slot-scope="scope">
                <span v-if="type==='approval'">{{scope.row.unitPrice}}</span>
                <el-input-number v-else is-decimal-zero v-model="scope.row.unitPrice" class="table-input" :controls="false" size="mini" :min="0" :precision="2">
                </el-input-number>
              </template>
            </el-table-column>

            <template v-for="(count,index) in deliveryDateCount">
            <el-table-column :resizable="false" label="交期" :column-key="'dateStr_'+count" :key="'dateStr_'+count"
              header-align="center">
              <div slot="header" class="delivery-date-header">
                <span>交期</span>
                <div class="delivery-date-handle" v-if="type!=='approval'">
                  <span style="color:#ff0000;margin-left:5px" title="删除交期" @click="delDeliveryDate(index)">
                    <i class="el-icon-close"></i>
                  </span>
                </div>
              </div>
              <el-table-column label="日期" min-width="140px" :column-key="'deliveryDate_'+count" :key="'deliveryDate_'+count" align="center">
                <template slot-scope="scope">
                  <template v-if="type==='approval'">
                  <span v-if="scope.row.deliveryDateList[index].date!==null">
                    {{moment(scope.row.deliveryDateList[index].date).format('YYYY-MM-DD')}}
                  </span>
                  </template>
                  <el-date-picker v-else class="table-input" v-model="scope.row.deliveryDateList[index].date" size="mini" type="date" value-format="timestamp" :editable="false">
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="数量" min-width="140px" :column-key="'deliveryCount_'+count" :key="'deliveryCount_'+count" align="center">
                <template slot-scope="scope">
                  <span v-if="type==='approval'">{{scope.row.deliveryDateList[index].count}}</span>
                  <el-input-number v-else v-model="scope.row.deliveryDateList[index].count" class="table-input" :controls="false" size="mini" :min="0" :precision="0">
                  </el-input-number>
                </template>
              </el-table-column>
            </el-table-column>
            </template>

            <el-table-column label="订单数" min-width="140px" column-key="orderTotal" key="orderTotal" align="center">
              <template slot-scope="scope">
                <span v-if="type==='approval'||!orderTotalCanUpdate(scope.row)">{{scope.row.orderTotal}}</span>
                <el-input-number v-else v-model="scope.row.orderTotal" class="table-input" :controls="false" size="mini" :min="0" :precision="0">
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="金额" min-width="120px" column-key="materialSumPrice" key="materialSumPrice" align="center">
              <template slot-scope="scope">
                <span>{{getSumPrice(scope.row)}}</span>
              </template>
            </el-table-column>
            <el-table-column :resizable="false" label="图片" width="80px" column-key="picUrl" key="picUrl" align="center">
              <template slot-scope="scope">
                <img-button :readonly="type==='approval'" v-model="scope.row.picUrl" size="mini" type="text" :button-text="type==='approval'?'查看图片':'设置图片'">
                </img-button>
              </template>
            </el-table-column>

            <el-table-column v-if="type!=='approval'" :resizable="false" label="操作" width="80px" column-key="handle" key="handle" fixed="right" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="deleteOrder(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          
            <template slot="append" v-if="type!=='approval'">
              <div class="add-row" :class="{'has-data':orderForm.orderDataList.length>0}" :style="{width:tableWidth}" @click="addOrder">
                <i class="el-icon-plus"></i>
                <span>新增</span>
              </div>
            </template>
          </el-table>
        </div>
        <div style="margin-top:10px">
          <business-material-table :materials="orderForm.materialBomList"></business-material-table>
        </div>
        <div class="business-order-form-remark">
          <div>
            <span style="font-size:18px;margin-right:10px">客户要求</span>
            <el-button size="small" type="primary" @click="toSettingOrderRemark">编辑</el-button>
          </div>
          <div style="margin-top:5px">
            <rich-editor disabled v-model="orderForm.orderRemark"></rich-editor>
          </div>
        </div>
      </div>
      </template>

      <el-dialog append-to-body fullscreen class="dialog-fullscreen" title="设置物料" :visible.sync="openSetting" @closed="selectOrder=null">
        <div style="height:100%;overflow:auto">
          <material-setting v-if="openSetting" :order="selectOrder" :order-form="orderForm" @setting-success="materialSettingSuccess"></material-setting>
        </div>
      </el-dialog>

      <el-dialog append-to-body fullscreen class="dialog-fullscreen" title="添加老花镜" :visible.sync="openDialog">
        <div style="height:100%;overflow:auto">
          <glasses-form v-if="openDialog" :type="type" :order-form="orderForm" @add-success="addGlassesSuccess">
          </glasses-form>
        </div>
      </el-dialog>

      <el-dialog append-to-body title="配置列显示" :visible.sync="openConfig" width="800px" top="10vh">
        <div style="height:calc(80vh - 54px);overflow:auto">
          <table-col-setting v-if="openConfig" :config.sync="tableConfig" :dropdown-option="dropdownOption"
            @setting-success="tableColSettingSuccess"></table-col-setting>
        </div>
      </el-dialog>

      <el-dialog append-to-body fullscreen class="dialog-fullscreen" title="编辑客户要求" :visible.sync="openRemark">
        <div style="height:100%;overflow:auto;padding:0 10px;">
          <rich-editor v-if="openRemark" v-model="orderForm.orderRemark" ref="richEditor">
            <template slot="append">
              <el-button type="primary" size="medium" @click="toEditText">确定</el-button>
            </template>
          </rich-editor>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    props: {
      order: {
        type: Object,
        default: function () {
          return null;
        }
      },
      type: {
        type: String,
        default: 'add'
      },
      dropdownOption: {
        type: Object,
        default: function () {
          return {};
        }
      },
      user: {
        type: Object,
        required: true
      }
    },

    computed: {
      glassesMaterialList: function () {
        var orderForm = this.orderForm;
        if (orderForm === null) {
          return [];
        }
        return orderForm.glassesMaterialList;
      },

      deliveryDateCount: function () {
        var orderForm = this.orderForm;
        if (orderForm === null) {
          return 0;
        }
        return orderForm.deliveryDateCount;
      },

      totalMomey: function () {
        var orderForm = this.orderForm;
        if (orderForm === null) {
          return 0;
        }

        var sumMomey = _.sumBy(orderForm.orderDataList, function (order) {
          var unitPrice = order.unitPrice;
          var orderTotal = order.orderTotal;
          if (unitPrice === undefined || orderTotal === undefined) {
            return 0;
          }
          return unitPrice * orderTotal;
        });
        sumMomey = _.round(sumMomey, 4);
        return sumMomey;
      }
    },

    data: function () {
      return {
        loading: false,
        tableConfig: null,
        orderList: [],
        custmerList: [],
        orderForm: null,
        orderTypeList: ['生产订单', '返工单', '打样单', '大货单'],
        openDialog: false,
        openConfig: false,
        openSetting: false,
        openRemark: false,
        selectOrder: null,
        tableWidth: '100%',
        showPopver: false
      };
    },

    created: function () {
      this.initData();
    },

    methods: {
      initData: function () {
        this.loading = true;
        var self = this;
        Promise.all([
          this.setMaterialTypeConfig(),
          this.setBomOrderList(),
          this.setCustmerList()
        ]).then(function () {
          return self.getOrderForm().then(function (orderForm) {
            self.loading = false;
            self.orderForm = orderForm;
            self.tableWidthEvent();
            return orderForm;
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      tableWidthEvent: function () {
        var self = this;
        this.$nextTick(function () {
          var $table = $(this.$el).find('.el-table__header-wrapper table');
          $table.resize(function () {
            self.setTableWidth();
          });
          self.setTableWidth();
        });
      },

      setMaterialTypeConfig: function () {
        var self = this;
        return ModuleUtil.getMaterialTypeConfig().then(function (tableConfig) {
          self.tableConfig = tableConfig;
          return tableConfig;
        });
      },

      setBomOrderList: function () {
        var self = this;
        return ModuleUtil.getBomOrderList().then(function (orderList) {
          self.orderList = orderList;
          return orderList;
        });
      },

      setCustmerList: function () {
        var self = this;
        return ModuleUtil.getCustmerList(this.dropdownOption).then(function (custmerList) {
          self.custmerList = custmerList;
          return custmerList;
        });
      },

      getOrderForm: function () {
        var type = this.type;
        if (type === 'add') {
          var orderForm = new BusinessOrderFormModel();
          return Promise.resolve(orderForm);
        }

        var order = this.order;
        var self = this;
        return ModuleUtil.getBusinessOrderDataById(order).then(function (businessOrder) {
          var factoryNo = businessOrder.titleBean.factoryNo;
          return ModuleUtil.getBomOrderDetail(factoryNo).then(function (materialList) {
            var orderForm = new BusinessOrderFormModel(businessOrder, self.orderList);
            orderForm.resetMaterialData(materialList);
            if (type === 'approval' && order.applyId !== null) {
              return ModuleUtil.getBeforeUpdateBusinessOrder(order, orderForm).then(function (beforeBusinessOrder) {
                var beforeOrder = new BusinessOrderFormModel(beforeBusinessOrder, self.orderList);
                orderForm.setCheckUpdate(beforeOrder);
                return orderForm;
              });
            }
            return orderForm;
          });
        });
      },

      bomOrderChange: function () {
        var orderForm = this.orderForm;
        var bomOrder = orderForm.bomOrder;
        if (bomOrder === '') {
          return;
        }

        this.loading = true;
        var self = this;
        ModuleUtil.getBomOrderDetail(bomOrder.factoryNo).then(function (materialList) {
          var flag = true;
          for (var i = 0; i < materialList.length; i++) {
            var material = materialList[i];
            if (material.bomType !== 4) {
              var materialCode = material.materialCode;
              if (SysUtil.isEmpty(materialCode)) {
                flag = false;
                break;
              }
            }
          }

          if (flag) {
            orderForm.resetMaterialData(materialList);
            orderForm.canSave = true;
          } else {
            orderForm.resetMaterialData([]);
            orderForm.canSave = false;
          }
          orderForm.orderDataList = [];
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      addOrder: function () {
        var orderForm = this.orderForm;
        var bomOrder = orderForm.bomOrder;
        if (bomOrder === '') {
          this.$message('请先选择工厂型号');
          return;
        }

        var canSave = orderForm.canSave;
        if (!canSave) {
          this.$message('该bom清单含有无物料代码物料，不能新增');
          return;
        }

        orderForm.addOrder();
      },

      deleteOrder: function (order) {
        this.orderForm.deleteOrder(order);
      },

      addGlasses: function () {
        this.openDialog = true;
      },

      addGlassesSuccess: function () {
        this.openDialog = false;
      },

      delGlasses: function (glasses) {
        this.orderForm.delGlasses(glasses);
      },

      addDeliveryDate: function () {
        this.orderForm.addDeliveryDate();
      },

      delDeliveryDate: function (index) {
        this.orderForm.delDeliveryDate(index);
      },

      orderTotalCanUpdate: function (order) {
        var count = order.getTotalGlassesCount();
        return count === undefined;
      },

      deliveryCountChange: function (order) {
        var count = order.getTotalGlassesCount();
        if (count !== undefined) {
          order.orderTotal = count;
        }
      },

      toSelectMaterial: function (order, column) {
        if (this.type === 'approval') {
          return;
        }

        if (this.setMaterialColumnClassName(column) !== 'is-button') {
          return;
        }

        this.selectOrder = order;
        this.openSetting = true;
      },

      materialSettingSuccess: function () {
        this.openSetting = false;
      },

      toCreateOrder: function (data) {
        var orderForm = this.orderForm;
        orderForm.newOrderNo = data.orderNo;
        this.ensure('newAdd');
      },

      ensure: function (type) {
        var orderForm = this.orderForm;
        var code = orderForm.checkValid();
        if (code !== '') {
          if (typeof code === 'string') {
            var msg = i18n.getMsg(`bomBusiness.businessOrder.error.${code}`);
            this.$alert(msg, '信息');
            return;
          } else {
            var index = code.index;
            var msg = i18n.getMsg(`bomBusiness.businessOrder.error.${code.code}`);
            msg = `在第${index+1}行，${msg}`;
            this.$alert(msg, '信息');
            return;
          }
        }

        var canSave = orderForm.canSave;
        if (!canSave) {
          var msg = '该bom清单含有无物料代码物料，无法生成商务订单';
          this.$alert(msg, '信息');
          return;
        }

        var bomOrder = orderForm.bomOrder;
        this.loading = true;
        var self = this;
        ajaxRequest('createOrderForBomOrder/getWasteRateForBomSelf', {
          serialNo: bomOrder.serialNo
        }).then(function (wasteRateList) {
          if (type === undefined) {
            type = self.type;
          }
          var PromiseList = [];
          if (type === 'add') {
            PromiseList.push(self.toAddOrder(orderForm, wasteRateList));
          } else if (type === 'update') {
            PromiseList.push(self.toUpdateOrder(orderForm, wasteRateList));
          } else if (type === 'applyUpdate') {
            PromiseList.push(self.toApplyUdateOrder(orderForm, wasteRateList));
          } else if (type === 'newAdd') {
            PromiseList.push(self.toNewAddOrder(orderForm, wasteRateList));
          } else {
            self.loading = false;
            return;
          }

          Promise.all(PromiseList).then(function (res) {
            res = res[0];
            self.loading = false;
            var data = res.data;
            var msg = res.msg;
            self.$alert(msg, '信息', {
              callback: function () {
                if (type === 'approval') {
                  self.$emit('approval-success', data);
                } else if (type === 'newAdd') {
                  self.$emit('newadd-success', data);
                } else {
                  self.$emit('save-success', data);
                }
              }
            });
          }).catch(function () {
            self.loading = false;
          });
        });
      },

      toAddOrder: function (orderForm, wasteRateList) {
        var postData = orderForm.getObject('add', wasteRateList);
        if (typeof postData === 'string') {
          this.$alert(postData, '信息');
          return Promise.resolve();
        }

        return ajaxRequest('createOrderForBomOrder/saveBomOrderBusiness', {
          dataStr: JSON.stringify(postData)
        }).then(function (data) {
          return {
            data: data,
            msg: '商务订单新增成功'
          };
        });
      },

      toUpdateOrder: function (orderForm, wasteRateList) {
        var postData = orderForm.getObject('update', wasteRateList);
        if (typeof postData === 'string') {
          this.$alert(postData, '信息');
          return Promise.resolve();
        }

        return ajaxRequest('createOrderForBomOrder/updateBomOrderBusiness', {
          dataStr: JSON.stringify(postData)
        }).then(function (data) {
          return {
            data: data,
            msg: '商务订单修改成功'
          };
        });
      },

      toApplyUdateOrder: function (orderForm, wasteRateList) {
        var postData = orderForm.getObject('update', wasteRateList, this.user);
        if (typeof postData === 'string') {
          this.$alert(postData, '信息');
          return Promise.resolve();
        }

        return ajaxRequest('createOrderForBomOrder/saveBomOrderBusinessApply', {
          dataStr: JSON.stringify(postData)
        }).then(function (data) {
          return {
            data: data,
            msg: '商务订单申请修改成功'
          };
        });
      },

      toNewAddOrder: function (orderForm, wasteRateList) {
        var postData = orderForm.getObject('add', wasteRateList);
        if (typeof postData === 'string') {
          this.$alert(postData, '信息');
          return Promise.resolve();
        }

        this.showPopver = false;
        postData.titleBean.orderNo = orderForm.newOrderNo;
        return ajaxRequest('createOrderForBomOrder/saveBomOrderBusiness', {
          dataStr: JSON.stringify(postData)
        }).then(function (data) {
          return {
            data: data,
            msg: '保存为新商务订单成功'
          };
        });
      },

      approvalOrder: function (status) {
        this.loading = true;
        var self = this;
        ModuleUtil.approvalBusniessOrder(this.order, this.orderForm, status).then(function (msg) {
          self.loading = false;
          self.$alert(msg, '信息', {
            callback: function () {
              self.$emit('approval-success');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      getMaterialInfo: function (order, materialType, field) {
        return order.getMaterialInfoData(materialType, field);
      },

      getSumPrice: function (order) {
        var unitPrice = order.unitPrice;
        var orderTotal = order.orderTotal;
        if (unitPrice === undefined || orderTotal === undefined) {
          return '';
        }

        var sumPrice = unitPrice * orderTotal;
        sumPrice = _.round(sumPrice, 4);
        return sumPrice;
      },

      checkUpdate: function (field) {
        if (this.type !== 'approval') {
          return false;
        }

        var applyId = this.order.applyId;
        if (SysUtil.isEmpty(applyId)) {
          return false;
        }

        return this.orderForm.checkUpdate(field);
      },

      setCellClassName: function (option) {
        if (this.type !== 'approval') {
          return this.setMaterialColumnClassName(option.column);
        }

        var applyId = this.order.applyId;
        if (SysUtil.isEmpty(applyId)) {
          return;
        }
        var order = option.row;
        var column = option.column;
        var columnKey = column.columnKey;
        if (order.checkUpdate(columnKey)) {
          return 'has-table-update';
        }
        return;
      },

      setMaterialColumnClassName: function (column) {
        var columnKey = column.columnKey;
        if (columnKey.indexOf('_') === -1) {
          return;
        }
        var materialFields = ['materialName', 'materialModel', 'materialProviderName', 'materialColor', 'materialColorDescription'];
        var field = columnKey.split('_')[0];
        if (materialFields.indexOf(field) !== -1) {
          return 'is-button';
        }
        return;
      },

      settingColConfig: function () {
        this.openConfig = true;
      },

      tableColSettingSuccess: function () {
        this.openConfig = false;
      },

      hasField: function (columns, field) {
        return columns.indexOf(field) !== -1;
      },

      setTableWidth: function () {
        var self = this;
        this.$nextTick(function () {
          var $table = $(this.$el).find('.el-table__header-wrapper table');
          var tableWidth = $table.width();
          if (tableWidth === null) {
            return;
          }
          self.tableWidth = tableWidth + 'px';
        });
      },

      toSettingOrderRemark: function () {
        this.openRemark = true;
      },

      toEditText: function () {
        this.loading = true;
        var self = this;
        this.$refs.richEditor.calContent().then(function () {
          self.loading = false;
          self.openRemark = false;
        }).catch(function () {
          self.loading = false;
        });
      }
    },

    components: {
      ImgButton: ImgButton,
      GlassesForm: GlassesForm,
      TableColSetting: TableColSetting,
      NewBusinessOrder: NewBusinessOrder,
      MaterialSetting: MaterialSetting,
      BusinessMaterialTable: BusinessMaterialTable,
      RichEditor: RichEditor
    },

    template: template
  };
}();
